const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { Logger } = require('../utils/logger');
const { verifyIdentity } = require('../utils/identityVerification');
const { authenticateToken } = require('../middleware/auth');

/**
 * @swagger
 * tags:
 *   name: Users
 *   description: 用户管理API
 */

/**
 * @swagger
 * /api/users/list:
 *   get:
 *     summary: 获取用户列表
 *     tags: [Users]
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: keyword
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: pageNum
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码（兼容参数）
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量（兼容参数）
 *       - in: query
 *         name: username
 *         schema:
 *           type: string
 *         description: 用户名搜索
 *       - in: query
 *         name: nickname
 *         schema:
 *           type: string
 *         description: 昵称搜索
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 用户状态筛选
 *     responses:
 *       200:
 *         description: 成功获取用户列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/User'
 *                 pagination:
 *                   type: object
 *                   properties:
 *                     page:
 *                       type: integer
 *                     limit:
 *                       type: integer
 *                     total:
 *                       type: integer
 *                     totalPages:
 *                       type: integer
 *       500:
 *         description: 服务器错误
 */
// 获取用户列表
router.get('/list', async (req, res) => {
  const startTime = Date.now();
  let sql = `SELECT 
    u.id, 
    u.nickname, 
    u.phone, 
    u.realName,
    u.idCard,
    u.role,
    u.status, 
    u.created_at, 
    u.updated_at,
    u.remark,
    u.password,
    COUNT(DISTINCT c.id) as contract_count,
    COALESCE(SUM(p.payment_amount), 0) as total_payment_amount
  FROM user u
  LEFT JOIN contracts c ON u.id = c.user_id
  LEFT JOIN payments p ON c.id = p.contract_id`;
  let countSql = 'SELECT COUNT(DISTINCT u.id) as total FROM user u';
  let params = [];
  
  try {
    const { 
      page = 1, 
      limit = 10, 
      keyword = '',
      pageNum = 1,
      pageSize = 10,
      realName = '',
      phone = '',
      status = ''
    } = req.query;
    
    // 兼容不同的参数名称
    const currentPage = pageNum || page;
    const currentLimit = pageSize || limit;
    const searchKeyword = realName || phone || keyword;
    const offset = (currentPage - 1) * currentLimit;
    let whereConditions = [];
    
    // 添加搜索条件
    if (searchKeyword) {
      whereConditions.push('(u.realName LIKE ? OR u.phone LIKE ?)');
      params.push(`%${searchKeyword}%`, `%${searchKeyword}%`);
    }
    
    // 添加状态筛选条件
    if (status !== '') {
      whereConditions.push('u.status = ?');
      params.push(status);
    }
    
    // 组合WHERE条件
    if (whereConditions.length > 0) {
      const whereClause = ' WHERE ' + whereConditions.join(' AND ');
      sql += whereClause;
      countSql += whereClause;
    }
    
    // 添加GROUP BY和分页
    sql += ' GROUP BY u.id, u.nickname, u.phone, u.idCard, u.realName, u.role, u.status, u.created_at, u.updated_at, u.remark, u.password ORDER BY u.created_at DESC LIMIT ? OFFSET ?';
    
    // 确保分页参数被添加到params数组中
    const paginationParams = [parseInt(currentLimit), parseInt(offset)];
    params = params.concat(paginationParams);
    
    // 执行查询
    const [users] = await db.query(sql, params);
    
    // 为count查询准备参数（不包括LIMIT和OFFSET）
    let countParams = [];
    if (searchKeyword) {
      countParams.push(`%${searchKeyword}%`, `%${searchKeyword}%`);
    }
    if (status !== '') {
      countParams.push(status);
    }
    
    const [countResult] = await db.query(countSql, countParams);
    
    // 记录数据库操作日志
    Logger.logDatabase('SELECT_USERS_LIST', sql, params, null, [users]);
    
    const responseData = {
      code: 200,
      data: users,
      message: '获取用户列表成功',
      pagination: {
        page: parseInt(currentPage),
        limit: parseInt(currentLimit),
        total: countResult[0].total,
        totalPages: Math.ceil(countResult[0].total / currentLimit)
      }
    };
    
    // 记录成功的API访问 - 在发送响应前设置头部
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    res.json(responseData);
    Logger.logRequest(req, res);
    
  } catch (error) {
    // 记录数据库错误
    Logger.logDatabase('SELECT_USERS_LIST', sql || 'N/A', params || [], error);
    
    console.error('❌ [用户列表] 获取失败:', {
      error: error.message,
      stack: error.stack,
      query: req.query,
      timestamp: new Date().toISOString()
    });
    
    // 记录失败的API访问 - 在发送响应前设置头部
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    res.status(500).json({
      code: 500,
      message: '获取用户列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
    
    Logger.logRequest(req, res, error);
  }
});

/**
 * @swagger
 * /api/users/statistics:
 *   get:
 *     summary: 获取系统统计数据
 *     tags: [Users]
 *     responses:
 *       200:
 *         description: 成功获取统计数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "获取成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     userCount:
 *                       type: object
 *                       properties:
 *                         value:
 *                           type: integer
 *                           example: 1248
 *                         label:
 *                           type: string
 *                           example: "用户总数"
 *                         growth:
 *                           type: string
 *                           example: "+12.5% 较上月"
 *                     contractCount:
 *                       type: object
 *                       properties:
 *                         value:
 *                           type: integer
 *                           example: 356
 *                         label:
 *                           type: string
 *                           example: "合同总数"
 *                         growth:
 *                           type: string
 *                           example: "+8.3% 较上月"
 *                     totalRevenue:
 *                       type: object
 *                       properties:
 *                         value:
 *                           type: string
 *                           example: "¥284.8万"
 *                         label:
 *                           type: string
 *                           example: "总收入"
 *                         growth:
 *                           type: string
 *                           example: "+15.7% 较上月"
 *                     projectCount:
 *                       type: object
 *                       properties:
 *                         value:
 *                           type: integer
 *                           example: 89
 *                         label:
 *                           type: string
 *                           example: "项目总数"
 *                         growth:
 *                           type: string
 *                           example: "+6.2% 较上月"
 *       500:
 *         description: 服务器错误
 */
router.get('/statistics', async (req, res) => {
  const startTime = Date.now();
  
  try {
    // 获取用户总数
    const [userCountResult] = await db.execute('SELECT COUNT(*) as total FROM user WHERE status != 0');
    const userCount = userCountResult[0].total;

    // 获取合同总数
    const [contractCountResult] = await db.execute('SELECT COUNT(*) as total FROM contracts');
    const contractCount = contractCountResult[0].total;

    // 获取总收入（所有已完成的支付金额）
    const [revenueResult] = await db.execute(`
      SELECT COALESCE(SUM(payment_amount), 0) as total_revenue 
      FROM payments 
      WHERE status = 'paid'
    `);
    const totalRevenue = revenueResult[0].total_revenue;

 

    // 格式化收入显示
    const formatRevenue = (amount) => {
      // 确保amount是数字类型
      const numAmount = parseFloat(amount) || 0;
      if (numAmount >= 10000) {
        return `${(numAmount / 10000).toFixed(1)}万`;
      } else {
        return `${numAmount.toFixed(2)}`;
      }
    };

    // 构造响应数据
    const statisticsData = {
      userCount: parseInt(userCount) || 0,
      contractCount: parseInt(contractCount) || 0,
      totalRevenue: formatRevenue(totalRevenue),
    };

    // 记录数据库操作日志
    Logger.logDatabase('SELECT_STATISTICS', 'Multiple queries for statistics', [], null, statisticsData);

    res.json({
      code: 200,
      message: "获取成功",
      data: statisticsData
    });

    // 记录成功的API访问
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    Logger.logRequest(req, res);

  } catch (error) {
    // 记录数据库错误
    Logger.logDatabase('SELECT_STATISTICS', 'Statistics queries', [], error);
    
    console.error('❌ [统计数据] 获取失败:', {
      error: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString()
    });

    // 记录失败的API访问
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    res.status(500).json({
      code: 500,
      message: '统计数据获取失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });

    Logger.logRequest(req, res, error);
  }
});

/**
 * @swagger
 * /api/users/{id}:
 *   get:
 *     summary: 获取单个用户信息
 *     tags: [Users]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 用户ID
 *     responses:
 *       200:
 *         description: 成功获取用户信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   $ref: '#/components/schemas/User'
 *       404:
 *         description: 用户不存在
 *       500:
 *         description: 服务器错误
 */
// 获取单个用户
router.get('/:id', async (req, res) => {
  const startTime = Date.now();
  try {
    const { id } = req.params;
    
    // 验证ID参数
    if (!id || isNaN(parseInt(id))) {
      const error = new Error('无效的用户ID参数');
      Logger.logRequest(req, res.status(400), error);
      return res.status(400).json({
        code: 400,
        message: '无效的用户ID参数'
      });
    }
    
    const sql = 'SELECT id, nickname as name, phone, idCard, realName, address, role, status, remark, created_at, updated_at FROM user WHERE id = ?';
    const params = [id];
    
    const [users] = await db.query(sql, params);
    
    // 记录数据库操作日志
    Logger.logDatabase('SELECT_USER_BY_ID', sql, params, null, [users]);
    
    if (users.length === 0) {
      console.warn('⚠️ [用户查询] 用户不存在:', {
        userId: id,
        ip: req.ip,
        timestamp: new Date().toISOString()
      });
      
      res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
      
      res.set('X-Response-Time', `${Date.now() - startTime}ms`);
      Logger.logRequest(req, res);
      return;
    }
    
    res.json({
      code: 200,
      data: users[0]
    });
    
    // 记录成功的API访问
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    Logger.logRequest(req, res);
    
  } catch (error) {
    // 记录数据库错误
    Logger.logDatabase('SELECT_USER_BY_ID', 'SELECT * FROM user WHERE id = ?', [req.params.id], error);
    
    console.error('❌ [用户详情] 获取失败:', {
      userId: req.params.id,
      error: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString()
    });
    
    // 记录失败的API访问 - 在发送响应前设置头部
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    res.status(500).json({
      code: 500,
      message: '获取用户详情失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
    
    Logger.logRequest(req, res, error);
  }
});

/**
 * @swagger
 * /api/users/addUser:
 *   post:
 *     summary: 新增用户
 *     tags: [Users]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *               - password
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               nickname:
 *                 type: string
 *                 description: 昵称
 *               password:
 *                 type: string
 *                 description: 密码
 *               phone:
 *                 type: string
 *                 description: 手机号
 *               email:
 *                 type: string
 *                 description: 邮箱
 *               role:
 *                 type: string
 *                 description: 角色
 *               status:
 *                 type: integer
 *                 description: 状态
 *     responses:
 *       200:
 *         description: 创建成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 用户创建成功
 *                 data:
 *                   type: object
 *                   properties:
 *                     id:
 *                       type: integer
 *                       description: 用户ID
 *       400:
 *         description: 请求参数错误
 *       409:
 *         description: 用户名已存在
 *       500:
 *         description: 服务器错误
 */
router.post('/addUser', async (req, res) => {
  const startTime = Date.now();
  
  try {
    const {
      nickname,
      password,
      phone,
      idCard,
      realName,
      address,
      role = 'user',
      status = 1,
      remark = ''
    } = req.body;
    
    // 参数验证
    if (!nickname || !password) {
      return res.status(200).json({
        code: 400,
        message: '昵称和密码不能为空'
      });
    }
    
    // 如果提供了真实姓名和身份证号，进行身份验证
    if (realName && idCard) {
      const verificationResult = await verifyIdentity(realName, idCard);
      if (!verificationResult.success) {
        return res.status(200).json({
          code: 400,
          message: verificationResult.message || "身份验证失败"
        });
      }
    }
    
    // 检查昵称和手机号是否已存在
    const checkUserSql = 'SELECT id FROM user WHERE nickname = ? OR phone = ?';
    const [existingUsers] = await db.query(checkUserSql, [nickname, phone]);
    
    if (existingUsers.length > 0) {
      return res.status(200).json({
        code: 409,
        message: '昵称或手机号已存在'
      });
    }
    
    // 插入新用户
    const insertSql = `INSERT INTO user 
      (nickname, password, phone, idCard, realName, address, role, status, remark, created_at, updated_at) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`;
    
    const insertParams = [nickname, password, phone, idCard, realName, address, role, status, remark];
    const [result] = await db.query(insertSql, insertParams);
    
    // 记录数据库操作日志
    Logger.logDatabase('INSERT_USER', insertSql, insertParams, null, result);
    
    const responseData = {
      code: 200,
      data: {
        id: result.insertId,
        nickname,
        phone,
        realName,
        role,
        status,
        remark,
        created_at: new Date().toISOString()
      },
      message: '用户创建成功'
    };
    
    res.json(responseData);
    
    // 记录成功的API访问
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    Logger.logRequest(req, res);
    
  } catch (error) {
    // 记录数据库错误
    Logger.logDatabase('INSERT_USER', 'N/A', [], error);
    
    console.error('❌ [新增用户] 创建失败:', {
      error: error.message,
      stack: error.stack,
      body: req.body,
      timestamp: new Date().toISOString()
    });
    
    // 记录失败的API访问 - 在发送响应前设置头部
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    res.status(200).json({
      code: 500,
      message: '用户创建失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
    
    Logger.logRequest(req, res, error);
  }
});

/**
 * @swagger
 * /api/users/updateUser/{id}:
 *   put:
 *     summary: 更新用户信息
 *     tags: [Users]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 用户ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               nickname:
 *                 type: string
 *                 description: 昵称
 *               phone:
 *                 type: string
 *                 description: 手机号
 *               email:
 *                 type: string
 *                 description: 邮箱
 *               role:
 *                 type: string
 *                 description: 角色
 *               status:
 *                 type: integer
 *                 description: 状态
 *     responses:
 *       200:
 *         description: 更新成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 用户更新成功
 *       400:
 *         description: 请求参数错误
 *       404:
 *         description: 用户不存在
 *       500:
 *         description: 服务器错误
 */
router.put('/updateUser/:id', async (req, res) => {
  const startTime = Date.now();
  
  try {
    const { id } = req.params;
    const {
      nickname,
      phone,
      idCard,
      realName,
      address,
      role,
      status,
      remark
    } = req.body;
    
    // 参数验证
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: '用户ID不能为空'
      });
    }
    
    // 检查用户是否存在
    const checkUserSql = 'SELECT id FROM user WHERE id = ?';
    const [existingUser] = await db.query(checkUserSql, [id]);
    
    if (existingUser.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    // 如果更新了真实姓名和身份证号，进行身份验证
    if (realName && idCard) {
      const verificationResult = await verifyIdentity(realName, idCard);
      if (!verificationResult.success) {
        return res.status(400).json({
          code: 400,
          message: verificationResult.message || "身份验证失败"
        });
      }
    }
    
    // 如果更新昵称或手机号，检查是否与其他用户冲突
    if (nickname || phone) {
      const checkConflictSql = 'SELECT id FROM user WHERE (nickname = ? OR phone = ?) AND id != ?';
      const [conflictUsers] = await db.query(checkConflictSql, [nickname, phone, id]);
      
      if (conflictUsers.length > 0) {
        return res.status(409).json({
          code: 409,
          message: '昵称或手机号已被其他用户使用'
        });
      }
    }
    
    // 构建更新SQL
    let updateFields = [];
    let updateParams = [];
    
    if (nickname !== undefined) {
      updateFields.push('nickname = ?');
      updateParams.push(nickname);
    }
    if (phone !== undefined) {
      updateFields.push('phone = ?');
      updateParams.push(phone);
    }
    if (idCard !== undefined) {
      updateFields.push('idCard = ?');
      updateParams.push(idCard);
    }
    if (realName !== undefined) {
      updateFields.push('realName = ?');
      updateParams.push(realName);
    }
    if (address !== undefined) {
      updateFields.push('address = ?');
      updateParams.push(address);
    }
    if (role !== undefined) {
      updateFields.push('role = ?');
      updateParams.push(role);
    }
    if (status !== undefined) {
      updateFields.push('status = ?');
      updateParams.push(status);
    }
    if (remark !== undefined) {
      updateFields.push('remark = ?');
      updateParams.push(remark);
    }
    
    if (updateFields.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '没有提供要更新的字段'
      });
    }
    
    updateFields.push('updated_at = NOW()');
    updateParams.push(id);
    
    const updateSql = `UPDATE user SET ${updateFields.join(', ')} WHERE id = ?`;
    const [result] = await db.query(updateSql, updateParams);
    
    // 记录数据库操作日志
    Logger.logDatabase('UPDATE_USER', updateSql, updateParams, null, result);
    
    // 获取更新后的用户信息
    const getUserSql = 'SELECT id, nickname, phone, idCard, realName, address, role, status, remark, created_at, updated_at FROM user WHERE id = ?';
    const [updatedUser] = await db.query(getUserSql, [id]);
    
    const responseData = {
      code: 200,
      data: updatedUser[0],
      message: '用户更新成功'
    };
    
    res.json(responseData);
    
    // 记录成功的API访问
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    Logger.logRequest(req, res);
    
  } catch (error) {
    // 记录数据库错误
    Logger.logDatabase('UPDATE_USER', 'N/A', [], error);
    
    console.error('❌ [编辑用户] 更新失败:', {
      error: error.message,
      stack: error.stack,
      params: req.params,
      body: req.body,
      timestamp: new Date().toISOString()
    });
    
    // 记录失败的API访问 - 在发送响应前设置头部
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    res.status(500).json({
      code: 500,
      message: '用户更新失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
    
    Logger.logRequest(req, res, error);
  }
});

/**
 * @swagger
 * /api/users/deleteUser/{id}:
 *   delete:
 *     summary: 删除用户
 *     tags: [Users]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 用户ID
 *     responses:
 *       200:
 *         description: 删除成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 用户删除成功
 *       400:
 *         description: 请求参数错误
 *       404:
 *         description: 用户不存在
 *       500:
 *         description: 服务器错误
 */
router.delete('/deleteUser/:id', async (req, res) => {
  const startTime = Date.now();
  
  try {
    const { id } = req.params;
    
    // 参数验证
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: '用户ID不能为空'
      });
    }
    
    // 检查用户是否存在
    const checkUserSql = 'SELECT id, nickname FROM user WHERE id = ?';
    const [existingUser] = await db.query(checkUserSql, [id]);
    
    if (existingUser.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    // 检查用户是否有关联的合同
    const checkContractsSql = 'SELECT COUNT(*) as count FROM contracts WHERE user_id = ?';
    const [contractCount] = await db.query(checkContractsSql, [id]);
    
    if (contractCount[0].count > 0) {
      return res.status(409).json({
        code: 409,
        message: '该用户存在关联的合同，无法删除'
      });
    }
    
    // 删除用户
    const deleteSql = 'DELETE FROM user WHERE id = ?';
    const [result] = await db.query(deleteSql, [id]);
    
    // 记录数据库操作日志
    Logger.logDatabase('DELETE_USER', deleteSql, [id], null, result);
    
    const responseData = {
      code: 200,
      data: {
        id: parseInt(id),
        nickname: existingUser[0].nickname,
        deleted: true
      },
      message: '用户删除成功'
    };
    
    res.json(responseData);
    
    // 记录成功的API访问
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    Logger.logRequest(req, res);
    
  } catch (error) {
    // 记录数据库错误
    Logger.logDatabase('DELETE_USER', 'N/A', [], error);
    
    console.error('❌ [删除用户] 删除失败:', {
      error: error.message,
      stack: error.stack,
      params: req.params,
      timestamp: new Date().toISOString()
    });
    
    // 记录失败的API访问
    // 记录失败的API访问 - 在发送响应前设置头部
    res.set('X-Response-Time', `${Date.now() - startTime}ms`);
    res.status(500).json({
      code: 500,
      message: '用户删除失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
    
    Logger.logRequest(req, res, error);
  }
});


/**
 * @swagger
 * /api/users/verifyIdentity:
 *   post:
 *     summary: 验证身份证和姓名是否匹配
 *     tags: [Users]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - name
 *               - idCard
 *             properties:
 *               name:
 *                 type: string
 *                 description: 真实姓名
 *                 example: "张三"
 *               idCard:
 *                 type: string
 *                 description: 身份证号码
 *                 example: "110101199001011234"
 *     responses:
 *       200:
 *         description: 验证结果
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   description: 验证是否成功
 *                 message:
 *                   type: string
 *                   description: 验证结果消息
 *                 data:
 *                   type: object
 *                   description: 验证详情（成功时返回）
 *                 code:
 *                   type: string
 *                   description: 错误代码（失败时返回）
 *       400:
 *         description: 参数错误
 *       500:
 *         description: 服务器内部错误
 */
router.post('/verifyIdentity', async (req, res) => {
  try {
    const { name, idCard } = req.body;
    
    // 参数验证
    if (!name || !idCard) {
      Logger.logWarning('身份证验证失败：缺少必要参数', { name, idCard });
      return res.status(400).json({
        success: false,
        message: '请提供姓名和身份证号码'
      });
    }
    
    // 验证身份证格式（简单验证）
    const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!idCardRegex.test(idCard)) {
      Logger.logWarning('身份证验证失败：身份证格式不正确', { name, idCard });
      return res.status(400).json({
        success: false,
        message: '身份证号码格式不正确'
      });
    }
    
    // 记录请求
    Logger.logInfo('开始身份证验证', { name, idCard: idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') });
    
    // 调用验证函数
    const result = await verifyIdentity(name, idCard);
    
    // 记录结果
    Logger.logInfo('身份证验证完成', { 
      name, 
      idCard: idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2'),
      success: result.success 
    });
    
    res.json(result);
  } catch (error) {
    Logger.logError('身份证验证异常', { error: error.message });
    res.status(500).json({ 
      success: false,
      message: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误' 
    });
  }
});
/**
 * @swagger
 * /api/users/updatePassword: 
 *   post:
 *     summary: 修改用户密码
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - currentPassword
 *               - newPassword
 *             properties:
 *               currentPassword:
 *                 type: string
 *                 description: 当前密码
 *               newPassword:
 *                 type: string
 *                 description: 新密码，长度至少6位
 *     responses:
 *       200:
 *         description: 密码修改成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 密码修改成功
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 未授权或当前密码错误
 *       500:
 *         description: 服务器内部错误
 */
router.put('/updatePassword', authenticateToken, async (req, res) => {
  const startTime = Date.now();
  
  try {
    const { currentPassword, newPassword } = req.body;
    const userId = req.user.id;
    
    // 参数验证
    if (!currentPassword || !newPassword) {
      Logger.logError('修改密码失败：缺少必要参数', { userId, duration: Date.now() - startTime });
      return res.status(400).json({
        code: 400,
        message: '请提供当前密码和新密码'
      });
    }
    
    // 验证新密码长度
    if (newPassword.length < 6) {
      Logger.logError('修改密码失败：新密码长度不足', { userId, duration: Date.now() - startTime });
      return res.status(400).json({
        code: 400,
        message: '新密码长度至少为6位'
      });
    }
    
    // 查询用户当前密码
    const [userRows] = await db.execute(
      'SELECT password FROM user WHERE id = ?',
      [userId]
    );
    
    if (userRows.length === 0) {
      Logger.logError('修改密码失败：用户不存在', { userId, duration: Date.now() - startTime });
      return res.status(401).json({
        code: 401,
        message: '用户不存在'
      });
    }
    
    const user = userRows[0];
    
    // 验证当前密码
    if (user.password !== currentPassword) {
      Logger.logError('修改密码失败：当前密码错误', { userId, duration: Date.now() - startTime });
      return res.status(401).json({
        code: 401,
        message: '当前密码错误'
      });
    }
    
    // 更新密码
    await db.execute(
      'UPDATE user SET password = ? WHERE id = ?',
      [newPassword, userId]
    );
    
    Logger.logInfo('密码修改成功', { userId, duration: Date.now() - startTime });
    res.json({
      code: 200,
      message: '密码修改成功'
    });
  } catch (error) {
    Logger.logError('修改密码异常', { error: error.message, duration: Date.now() - startTime });
    res.status(500).json({
      code: 500,
      message: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});


module.exports = router;